﻿using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Common.Enums;
using Com.JunCaiSoft.Common.Struct;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.Common.Dao
{
    public abstract class CoreDAL<T> where T : class,new()
    {
        /// <summary>
        /// 数据层上下文类
        /// </summary>
        protected DbContext baseContext { get; set; }
        /// <summary>
        /// 数据层通用操作类构造函数
        /// </summary>
        /// <param name="context"></param>
        public CoreDAL(DbContext context)
        {
            baseContext = context;
        }
        /// <summary>
        /// 传入要插入数据库的实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Insert(T t)
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Set<T>().Add(t);
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要插入数据库的实体（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Insert<TEntity>(TEntity t) where TEntity : class, new()
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Set<TEntity>().Add(t);
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要插入数据库的实体列表
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public virtual int Insert(List<T> entities)
        {
            
            int result = 0;
            if (entities == null)
            {
                return result;
            }
            var list = entities.GetEnumerator();
            while (list.MoveNext())
            {
                result += Insert(list.Current);
            }
            return result;
        }
        /// <summary>
        /// 传入要插入数据库的实体列表（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entities"></param>
        /// <returns></returns>
        public virtual int Insert<TEntity>(List<TEntity> entities) where TEntity : class, new()
        {
            int result = 0;
            if (entities == null)
            {
                return result;
            }
            var list = entities.GetEnumerator();
            while (list.MoveNext())
            {
                result += Insert(list.Current);
            }
            return result;
        }
        /// <summary>
        /// 传入要从数据库删除的实体主键
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual int Delete(object id)
        {
            var deleteOne = Get(id);
            return Delete(deleteOne);
        }
        /// <summary>
        /// 传入要从数据库删除的实体主键（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity">指定任意实体</typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual int Delete<TEntity>(object id) where TEntity : class, new()
        {
            var deleteOne = Get(id);
            return Delete<TEntity>(deleteOne);
        }
        /// <summary>
        /// 传入要从数据库删除的实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Delete(T t)
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Entry<T>(t).State = EntityState.Deleted;
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要从数据库删除的实体（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Delete<TEntity>(TEntity t) where TEntity : class, new()
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Entry(t).State = EntityState.Deleted;
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 删除所有实体
        /// </summary>
        /// <returns></returns>
        public virtual int DeleteAll()
        {
            return DeleteList(List());
        }
        /// <summary>
        /// 传入要从数据库删除的实体主键列表（按查询条件）
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual int DeleteList(Expression<Func<T, bool>> where)
        {
            var deleteList = List(where);
            return DeleteList(deleteList);
        }
        /// <summary>
        /// 传入要从数据库删除的实体主键列表（按查询条件,可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual int DeleteList<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : class, new()
        {
            var deleteList = List<TEntity>(where);
            return DeleteList(deleteList);
        }
        /// <summary>
        /// 传入要从数据库删除的实体
        /// </summary>
        /// <param name="deleteList"></param>
        /// <returns></returns>
        public virtual int DeleteList(List<T> deleteList)
        {
            foreach (var item in deleteList.ToArray())
            {
                baseContext.Entry(item).State = EntityState.Deleted;
            }
            var result = baseContext.SaveChanges();
            return result;
        }
        /// <summary>
        /// 传入要从数据库删除的实体(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="deleteList"></param>
        /// <returns></returns>
        public virtual int DeleteList<TEntity>(List<TEntity> deleteList) where TEntity : class, new()
        {
            foreach (var item in deleteList.ToArray())
            {
                baseContext.Entry(item).State = EntityState.Deleted;
            }
            var result = baseContext.SaveChanges();
            return result;
        }
        /// <summary>
        /// 传入要从数据库更新的实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Update(T t)
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Set<T>().Attach(t);
            baseContext.Entry(t).State = EntityState.Modified;
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要从数据库更新的实体（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual int Update<TEntity>(TEntity t) where TEntity : class, new()
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Set<TEntity>().Attach(t);
            baseContext.Entry(t).State = EntityState.Modified;
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要从数据库更新的实体（传入原始数据的ID）
        /// </summary>
        /// <param name="t"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual int Update(T t,object id)
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Entry(Get(id)).CurrentValues.SetValues(t);
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要从数据库更新的实体（传入原始数据的ID）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="t"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual int Update<TEntity>(TEntity t,object id) where TEntity : class, new()
        {
            if (t == null)
            {
                throw new Exception("传入的对象为空值！");
            }
            baseContext.Entry(Get(id)).CurrentValues.SetValues(t);
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要在数据库作出批量跟新的lamp表达式
        /// </summary>
        /// <param name="where"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public virtual int Update(Expression<Func<T, bool>> where, Dictionary<string, object> dic)
        {
            IEnumerable<T> result = baseContext.Set<T>().Where(where).ToList();
            Type type = typeof(T);
            var propertyList = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).ToList();
            foreach (var item in result)
            {
                foreach (var itemInner in propertyList)
                {
                    var propertyName = itemInner.Name;
                    if (dic.ContainsKey(propertyName))
                    {
                        itemInner.SetValue(item, dic[propertyName], null);
                    }
                }
            }
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要在数据库作出批量跟新的lamp表达式(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public virtual int Update<TEntity>(Expression<Func<TEntity, bool>> where, Dictionary<string, object> dic) where TEntity : class, new()
        {
            IEnumerable<TEntity> result = baseContext.Set<TEntity>().Where(where).ToList();
            Type type = typeof(TEntity);
            var propertyList = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).ToList();
            foreach (var item in result)
            {
                foreach (var itemInner in propertyList)
                {
                    var propertyName = itemInner.Name;
                    if (dic.ContainsKey(propertyName))
                    {
                        itemInner.SetValue(item, dic[propertyName], null);
                    }
                }
            }
            return baseContext.SaveChanges();
        }
        /// <summary>
        /// 传入要获取实体的主键
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual T Get(object id)
        {
            return baseContext.Set<T>().Find(id);
        }
        /// <summary>
        /// 传入要获取实体的主键(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity Get<TEntity>(object id) where TEntity : class, new()
        {
            return baseContext.Set<TEntity>().Find(id);
        }
        /// <summary>
        /// 传入要获取单体查询的lamp表达式，仅适用于单个实体查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual T Get(Expression<Func<T, bool>> where)
        {
            return baseContext.Set<T>().Where(where).SingleOrDefault();
        }
        /// <summary>
        /// 传入要获取单体查询的lamp表达式，仅适用于单个实体查询(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual TEntity Get<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : class, new()
        {
            return baseContext.Set<TEntity>().Where(where).SingleOrDefault();
        }
        /// <summary>
        /// 获取所有实体
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <returns></returns>
        public virtual List<T> List()
        {
            return List<T>(null);
        }
        /// <summary>
        /// 获取所有实体（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public virtual List<TEntity> List<TEntity,TKey>() where TEntity : class, new()
        {
            return List<TEntity,TKey>(null);
        }
        /// <summary>
        /// 获取该实体在数据库中的记录条数
        /// </summary>
        /// <returns></returns>
        public virtual long TotalCount()
        {
            return baseContext.Set<T>().LongCount();
        }
        public virtual long TotalCount<TEntity>() where TEntity : class, new()
        {
            return baseContext.Set<TEntity>().LongCount();
        }
        /// <summary>
        /// 获取所有where条件下的无序实体
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual List<T> List(Expression<Func<T, bool>> where)
        {
            return List<T>(where, null);
        }
        /// <summary>
        /// 获取所有where条件下的无序实体（可指定任意数据库中存在的实体）
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual List<TEntity> List<TEntity,TKey>(Expression<Func<TEntity, bool>> where) where TEntity : class, new()
        {
            return List<TEntity,TKey>(where, null);
        }
        /// <summary>
        /// 获取所有实体，传入OrderBy，排序条件lamp表达式
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="orderBy"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<T> List<TKey>(Expression<Func<T, TKey>> orderBy, OrderbyType orderType = OrderbyType.ase)
        {
            return List<TKey>(null, orderBy,orderType);
        }
        /// <summary>
        /// 获取所有实体，传入OrderBy，排序条件lamp表达式(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="orderBy"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<TEntity> List<TEntity,TKey>(Expression<Func<TEntity, TKey>> orderBy, OrderbyType orderType = OrderbyType.ase) where TEntity : class, new()
        {
            return List<TEntity,TKey>(null,orderBy, orderType);
        }
        /// <summary>
        /// 获取所有有条件的实体，传入where条件lamp表达式，传入orderby条件lamp表达式
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="where"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderbyType"></param>
        /// <returns></returns>
        public virtual List<T> List<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> orderBy,OrderbyType orderbyType = OrderbyType.ase)
        {
            IEnumerable<T> resultList = null;
            if(where == null && orderBy == null)
            {
                resultList = baseContext.Set<T>();
            }
            else if(where != null && orderBy == null)
            {
                resultList = baseContext.Set<T>().Where(where);
            }
            else if (where == null && orderBy != null)
            {
                if(orderbyType == OrderbyType.ase)
                {
                    resultList = baseContext.Set<T>().OrderBy(orderBy);
                }
                else
                {
                    resultList = baseContext.Set<T>().OrderByDescending(orderBy);
                }
            }
            else
            {
                if(orderbyType == OrderbyType.ase)
                {
                    resultList = baseContext.Set<T>().Where(where).OrderBy(orderBy);
                }
                else
                {
                    resultList = baseContext.Set<T>().Where(where).OrderByDescending(orderBy);
                }
                
            }
            return resultList.ToList();
        }
        /// <summary>
        /// 获取所有有条件的实体，传入where条件lamp表达式，传入orderby条件lamp表达式(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderbyType"></param>
        /// <returns></returns>
        public virtual List<TEntity> List<TEntity,TKey>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TKey>> orderBy, OrderbyType orderbyType = OrderbyType.ase) where TEntity : class, new()
        {
            IEnumerable<TEntity> resultList = null;
            if (where == null && orderBy == null)
            {
                resultList = baseContext.Set<TEntity>();
            }
            else if (where != null && orderBy == null)
            {
                resultList = baseContext.Set<TEntity>().Where(where);
            }
            else if (where == null && orderBy != null)
            {
                if (orderbyType == OrderbyType.ase)
                {
                    resultList = baseContext.Set<TEntity>().OrderBy(orderBy);
                }
                else
                {
                    resultList = baseContext.Set<TEntity>().OrderByDescending(orderBy);
                }
            }
            else
            {
                if (orderbyType == OrderbyType.ase)
                {
                    resultList = baseContext.Set<TEntity>().Where(where).OrderBy(orderBy);
                }
                else
                {
                    resultList = baseContext.Set<TEntity>().Where(where).OrderByDescending(orderBy);
                }

            }
            return resultList.ToList();
        }
        /// <summary>
        /// 根据条件获取多个实体
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public List<T> List(Expression<Func<T, bool>> condition, params OrderModelField[] orderByExpression)
        {
            //条件过滤
            var query = this.baseContext.Set<T>().Where(condition);

            //创建表达式变量参数
            var parameter = Expression.Parameter(typeof(T), "o");

            if (orderByExpression != null && orderByExpression.Length > 0)
            {
                for (int i = 0; i < orderByExpression.Length; i++)
                {
                    //根据属性名获取属性
                    var property = typeof(T).GetProperty(orderByExpression[i].propertyName);
                    //创建一个访问属性的表达式
                    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                    var orderByExp = Expression.Lambda(propertyAccess, parameter);

                    string OrderName = "";
                    if (i > 0)
                    {
                        OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy";
                    }
                    else
                        OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy";


                    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));

                    query = query.Provider.CreateQuery<T>(resultExp);
                }
            }
            
            return query.ToList();
        }
        /// <summary>
        /// 根据条件获取多个实体(自定义)
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public List<TEntity> List<TEntity>(Expression<Func<TEntity, bool>> condition, params OrderModelField[] orderByExpression) where TEntity : class, new()
        {
            //条件过滤
            var query = this.baseContext.Set<TEntity>().Where(condition);

            //创建表达式变量参数
            var parameter = Expression.Parameter(typeof(TEntity), "o");

            if (orderByExpression != null && orderByExpression.Length > 0)
            {
                for (int i = 0; i < orderByExpression.Length; i++)
                {
                    //根据属性名获取属性
                    var property = typeof(TEntity).GetProperty(orderByExpression[i].propertyName);
                    //创建一个访问属性的表达式
                    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                    var orderByExp = Expression.Lambda(propertyAccess, parameter);

                    string OrderName = "";
                    if (i > 0)
                    {
                        OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy";
                    }
                    else
                        OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy";


                    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(TEntity), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));

                    query = query.Provider.CreateQuery<TEntity>(resultExp);
                }
            }
            
            return query.ToList();
        }
        /// <summary>
        /// 获取当前分页所有实体，传入orderby条件lamp表达式进行排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="orderBy"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<T> ListByPage<TKey>(Expression<Func<T, TKey>> orderBy, int pageIndex, int pageSize, out long totalRecords, OrderbyType orderType = OrderbyType.ase)
        {
            return ListByPage<TKey>(null, orderBy, pageIndex, pageSize, out totalRecords,orderType);
        }
        /// <summary>
        /// 获取当前分页所有实体，传入orderby条件lamp表达式进行排序(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="orderBy"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<TEntity> ListByPage<TEntity,TKey>(Expression<Func<TEntity, TKey>> orderBy, int pageIndex, int pageSize, out long totalRecords, OrderbyType orderType = OrderbyType.ase) where TEntity : class, new()
        {
            return ListByPage(null, orderBy, pageIndex, pageSize, out totalRecords, orderType);
        }
        /// <summary>
        /// 获取所有where条件下lamp表达式的实体，并用orderby条件用lamp表达式进行排序（附带分页条件）
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="where"></param>
        /// <param name="orderBy"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<T> ListByPage<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> orderBy, int pageIndex, int pageSize, out long totalRecords, OrderbyType orderType = OrderbyType.ase)
        {
            if (where == null)
            {
                totalRecords = baseContext.Set<T>().LongCount();
                if (orderType == OrderbyType.ase)
                {
                    return baseContext.Set<T>().OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    return baseContext.Set<T>().OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            else
            {
                totalRecords = baseContext.Set<T>().Where(where).LongCount();
                if (orderType == OrderbyType.ase)
                {
                    return baseContext.Set<T>().Where(where).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    return baseContext.Set<T>().Where(where).OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
        }
        /// <summary>
        /// 获取所有where条件下lamp表达式的实体，并用orderby条件用lamp表达式进行排序（附带分页条件）(可指定任意数据库中存在的实体)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="where"></param>
        /// <param name="orderBy"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public virtual List<TEntity> ListByPage<TEntity,TKey>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TKey>> orderBy, int pageIndex, int pageSize, out long totalRecords, OrderbyType orderType = OrderbyType.ase) where TEntity : class, new()
        {
            

            if (where == null)
            {
                totalRecords = baseContext.Set<TEntity>().LongCount();
                if (orderType == OrderbyType.ase)
                {
                    return baseContext.Set<TEntity>().OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    return baseContext.Set<TEntity>().OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            else
            {
                totalRecords = baseContext.Set<TEntity>().Where(where).LongCount();
                if (orderType == OrderbyType.ase)
                {
                    return baseContext.Set<TEntity>().Where(where).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    return baseContext.Set<TEntity>().Where(where).OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
        }
        /// <summary>
        /// 根据条件获取多个实体
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public List<T> ListByPage(Expression<Func<T, bool>> condition, int pageIndex, int pageSize, out long total, params OrderModelField[] orderByExpression)
        {
            //条件过滤
            IQueryable<T> query;

            if(condition == null)
            {
                query = this.baseContext.Set<T>();
            }
            else
            {
                query = this.baseContext.Set<T>().Where(condition);
            }

            //创建表达式变量参数
            var parameter = Expression.Parameter(typeof(T), "o");

            if (orderByExpression != null && orderByExpression.Length > 0)
            {
                for (int i = 0; i < orderByExpression.Length; i++)
                {
                    //根据属性名获取属性
                    var property = typeof(T).GetProperty(orderByExpression[i].propertyName);
                    if(property != null)
                    {
                        //创建一个访问属性的表达式
                        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                        var orderByExp = Expression.Lambda(propertyAccess, parameter);

                        string OrderName = "";
                        if (i > 0)
                        {
                            OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy";
                        }
                        else
                            OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy";


                        MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));

                        query = query.Provider.CreateQuery<T>(resultExp);
                    }
                }
            }

            total = query.Count();
            return query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        /// <summary>
        /// 根据条件获取多个实体(自定义)
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public List<TEntity> ListByPage<TEntity>(Expression<Func<TEntity, bool>> condition, int pageIndex, int pageSize, out long total, params OrderModelField[] orderByExpression) where TEntity : class, new()
        {
            //条件过滤
            IQueryable<TEntity> query;

            if(condition == null)
            {
                query = this.baseContext.Set<TEntity>();
            }
            else
            {
                query = this.baseContext.Set<TEntity>().Where(condition);
            }

            //创建表达式变量参数
            var parameter = Expression.Parameter(typeof(TEntity), "o");

            if (orderByExpression != null && orderByExpression.Length > 0)
            {
                for (int i = 0; i < orderByExpression.Length; i++)
                {
                    //根据属性名获取属性
                    var property = typeof(TEntity).GetProperty(orderByExpression[i].propertyName);
                    //创建一个访问属性的表达式
                    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                    var orderByExp = Expression.Lambda(propertyAccess, parameter);

                    string OrderName = "";
                    if (i > 0)
                    {
                        OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy";
                    }
                    else
                        OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy";


                    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(TEntity), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));

                    query = query.Provider.CreateQuery<TEntity>(resultExp);
                }
            }

            total = query.Count();
            return query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        /// <summary>
        /// 通过SQL查询数据结果
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> QuerySQL<TEntity>(string sql, params object[] parameters) where TEntity: class, new()
        {
            IQueryable<TEntity> query = SqlQueryAssist.SqlQuery<TEntity>(baseContext,sql, parameters).AsQueryable();
            return query;
        }
        /// <summary>
        /// 通过SQL查询数据结果(分页）
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalRecords">总计条数</param>
        /// <param name="sql">SQL语句</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> QuerySQLByPage<TEntity>(int pageIndex, int pageSize, out long totalRecords,string sql, params object[] parameters) where TEntity : class, new()
        {
            totalRecords = SqlQueryAssist.SqlQuery<TEntity>(baseContext,sql).LongCount();

            IQueryable<TEntity> query = SqlQueryAssist.SqlQuery<TEntity>(baseContext, sql, parameters).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsQueryable();
            return query;
        }
        /// <summary>
        /// 通过带RowNumber Over的SQL语句快速分页查询
        /// </summary>
        /// <typeparam name="TEntity">泛型</typeparam>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页数据条数</param>
        /// <param name="totalRecords">总条数</param>
        /// <param name="orderBy"></param>
        /// <param name="colums"></param>
        /// <param name="tables"></param>
        /// <param name="where"></param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public virtual IQueryable<TEntity> QuerySQLByPageQuick<TEntity>(int pageIndex, int pageSize, out long totalRecords, string orderBy, string colums = null,string tables = null, string where = null, params object[] parameters) where TEntity : class, new()
        {
            SqlParameter para1 = new SqlParameter("@start", SqlDbType.Int);

            SqlParameter para2 = new SqlParameter("@end", SqlDbType.Int);

            para1.Value = (pageIndex - 1) * pageSize;

            para2.Value = pageIndex * pageSize + 1;

            if (String.IsNullOrEmpty(tables))
            {
                tables = typeof(TEntity).Name;
            }

            if (String.IsNullOrEmpty(colums))
            {
                colums = "*";
            }

            List<SqlParameter> arrary = new List<SqlParameter>();
            arrary.Add(para1); arrary.Add(para2);

            foreach (var item in parameters)
            {
                arrary.Add((SqlParameter)item);
            }

            var countSQL = "select 1 from " + tables + (where != null ? " where " + where : null);
            totalRecords = QuerySQL<TEntity>(countSQL, parameters).LongCount();

            var pageSQL = "select * from (" +
                                " select " +
                                "ROW_NUMBER () OVER (ORDER BY " + orderBy + ") AS rowid," + colums +
                                " from " + tables +
                                (where != null ? " where " + where : null) +
                                " ) a where a.rowid > @start AND a.rowid < @end";
            //" order by " + (orderBy == null ? orderby : orderBy);
            return QuerySQL<TEntity>(pageSQL, arrary.Select(x => ((ICloneable)x).Clone()).ToArray());
        }
        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        public int ExcuteSQLCommand(String sql,params object[] parameters)
        {
            return baseContext.Database.ExecuteSqlRaw(sql, parameters);
        }
    }
}
